package com.service;
import com.dao.AsAccountDao;
import com.dao.AsAccountDetailDao;
import com.dao.AsKeywordsDao;
import com.dao.AsSystemConfigDao;
import com.entity.*;
import com.utils.DateUtil;
import com.utils.JsonUtil;
import com.utils.Pager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

@Service
public class AsKeywordsService
{
    @Resource
    private AsKeywordsDao asKeywordsDao;

    @Resource
    private AsAccountDao asAccountDao;

    @Resource
    private AsAccountDetailDao asAccountDetailDao;

    @Resource
    private AsSystemConfigDao asSystemConfigDao;

    //根据当前用户 关键词 返回关键词申请管理datagrid的json格式数据
    public String returnKeywordsDataGridJsonStr( Integer agentId , String keywords , Integer page , Integer size )
    {
        Integer index = ( page - 1 ) * size;
        Integer total = asKeywordsDao.getKeywordsCount( agentId );
        ArrayList<AsKeywords> keywordsList = asKeywordsDao.getKeywordsOfAgent( agentId , keywords , index , size );
        Pager<AsKeywords> pager = new Pager<>();
        pager.setTotal( total );
        pager.setRows( keywordsList );
        String jsonStr = JsonUtil.toJsonStrWithDateTime( pager );
        System.out.println( jsonStr );

        return jsonStr;
    }

    //修改审核状态为审核中
    public String setChecking( AsKeywords keywords )
    {
        keywords.setCheckStatus( 1 );
        Integer resultCode = asKeywordsDao.updateOneKeywords( keywords );
        String jsonStr = JsonUtil.successOrNotJsonStr( resultCode );

        return jsonStr;
    }

    //修改审核状态为不通过
    public String setCheckIsNo( AsKeywords keywords )
    {
        keywords.setCheckStatus( 3 );
        Integer resultCode = asKeywordsDao.updateOneKeywords( keywords );
        String jsonStr = JsonUtil.successOrNotJsonStr( resultCode );

        return jsonStr;
    }

    //修改使用状态为不使用
    public String setNotUse( AsKeywords keywords )
    {
        keywords.setIsUse( false );
        Integer resultCode = asKeywordsDao.updateOneKeywords( keywords );
        String jsonStr = JsonUtil.successOrNotJsonStr( resultCode );

        return jsonStr;
    }

    //修改使用状态为使用
    public String setStartUse( AsKeywords keywords )
    {
        keywords.setIsUse( true );
        Integer resultCode = asKeywordsDao.updateOneKeywords( keywords );
        String jsonStr = JsonUtil.successOrNotJsonStr( resultCode );

        return jsonStr;
    }

    //提交关键词申请,返回提交结果(增加乐观锁)
    //通过注解开启事务管理 只要出现异常即回滚
    @Transactional( rollbackFor = Exception.class )
    public Integer submitKeywordsApplication( AsKeywords keywords , AsUser user , Integer detailType )
    {
        //首先查询表中是否存在该关键词
        Integer count = asKeywordsDao.keywordsExistOrNot( keywords.getKeywords() );
        Integer userId = user.getId();
        Double freezeMoney = keywords.getPreRegFrozenMoney();
        Integer resultCode = 0;
        if( count != 0 )
        {
            return resultCode;
        }
        //若表中不存在该关键词 将该关键词写入表
        keywords.setAgentId( user.getId() );
        keywords.setAgentName( user.getUserName() );
        keywords.setPrice( 0.0 );
        keywords.setOpenApp( false );
        //设置申请日期和到期日期
        Date passedDate = DateUtil.calculationDate( keywords.getServiceYears().longValue() );
        keywords.setPreRegDatetime( new Date() );
        keywords.setPreRegPassDatetime( passedDate );
        keywords.setRegDatetime( new Date() );
        keywords.setRegPassDatetime( passedDate );
        //设置当前状态 未过期
        keywords.setIsPass( 0 );
        //设置审核状态 已申请
        keywords.setCheckStatus( 0 );
        //设置使用状态为已使用
        keywords.setIsUse( true );
        resultCode = asKeywordsDao.addKeywords( keywords );
        //System.out.println( "第一次: " + resultCode );

        //根据用户id获取当前账户
        AsAccount userAccount = asAccountDao.getAccountByUserId( userId );
        //获取当前账户资金
        Double totalMoney = userAccount.getMoney();
        Double currentMoney = totalMoney - freezeMoney;
        userAccount.setMoney( currentMoney );
        userAccount.setMoneyBak( currentMoney );
        //当前账户冻结资金(冻结款)
        resultCode *= asAccountDao.updateAccount( userAccount );
        //System.out.println( "第二次: " + resultCode );

        //查询财务人员账户信息
        AsAccount financialAccount = new AsAccount();
        Map<String,Object> map = asAccountDao.getFinancialUserAccount();
        //获取财务账户version
        Integer financialVersion = (Integer)map.get( "version" );
        //System.out.println( "断点前");
        //System.out.println( "version: " + financialVersion );
        //System.out.println( "断点后");
        financialAccount.setUserId( (Integer)map.get( "userId" ) );
        Double financialTotalMoney = (Double)map.get( "money" );
        Double financialCurrentMoney = financialTotalMoney + freezeMoney;
        financialAccount.setMoney( financialCurrentMoney );
        financialAccount.setMoneyBak( financialCurrentMoney );
        financialAccount.setVersion( financialVersion );
        //财务人员账户增加资金(冻结款)
        resultCode *= asAccountDao.updateAccount( financialAccount );
        //System.out.println( "第三次: " + resultCode );

        //向账户明细表中添加数据
        //查询财务款项操作名称
        AsSystemConfig config = asSystemConfigDao.getFinancialType( detailType );
        AsAccountDetail detail = new AsAccountDetail();
        detail.setUserId( userId );
        detail.setDetailType( detailType );
        detail.setDetailTypeName( "[系统自动]" + config.getConfigValue() );
        detail.setMoney( freezeMoney );
        detail.setAccountMoney( currentMoney );
        detail.setDetailDateTime( new Date() );
        detail.setMemo( "[" + user.getUserName() + "]为客户[" + keywords.getCustomName() +
                "]进行关键词(" + keywords.getKeywords() + ")申请操作; 冻结" + user.getUserName() + "资金:" + freezeMoney + "元" );
        resultCode *= asAccountDetailDao.addOneDetail( detail );
        //System.out.println( "第四次: " + resultCode );

        //确保任意步骤执行失败(resultCode为0)后回滚
        if( resultCode == 0 )
        {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return resultCode;
    }

    //提交关键词续费,返回提交结果(增加乐观锁)
    //通过注解开启事务管理 只要出现异常即回滚
    @Transactional( rollbackFor = Exception.class )
    public Integer submitKeywordsRecharge(
            AsKeywords keywords , AsUser user ,
            Integer detailType , Double totalPrice )
    {
        //判断关键词状态是否过期
        Integer status = keywords.getIsPass();
        Integer userId = user.getId();
        Integer resultCode = 0;
        //根据id查询当前关键词
        AsKeywords old = asKeywordsDao.getOneKeyWordById( keywords.getId() );
        //获取续费年限
        Integer gainedYears = keywords.getServiceYears();
        //状态未过期 申请续费
        if( status == 0 )
        {
            //设置新的服务年限为原年限加新年限
            Integer oldYears = old.getServiceYears();
            keywords.setServiceYears( oldYears + gainedYears );
            //设置新的到期时间为原到期时间加新的年限
            Date regcPassDate = old.getRegPassDatetime();
            Date newPassDate = DateUtil.calculationDate( regcPassDate , gainedYears.longValue() );
            keywords.setRegPassDatetime( newPassDate );
            //设置价格为原价格加增加年限价格
            Double oldPrice = old.getPrice();
            keywords.setPrice( oldPrice + totalPrice );
            //将新的服务年限 到期日期 价格写入表中
            resultCode = asKeywordsDao.updateOneKeywords( keywords );
        }
        //状态已过期 申请续费
        else
        {
            //设置新的年限为当前选择年限
            keywords.setServiceYears( gainedYears );
            //设置新的到期日期
            Date newPassDate = DateUtil.calculationDate( gainedYears.longValue() );
            keywords.setRegPassDatetime( newPassDate );
            //设置新的price
            keywords.setPrice( totalPrice );
            //续费后设置状态为未过期
            keywords.setIsPass( 0 );
            //将新的服务年限 到期日期 价格写入表中
            resultCode = asKeywordsDao.updateOneKeywords( keywords );
        }

        //根据用户id获取当前账户
        AsAccount userAccount = asAccountDao.getAccountByUserId( userId );
        //获取当前账户资金
        Double totalMoney = userAccount.getMoney();
        Double currentMoney = totalMoney - totalPrice;
        userAccount.setMoney( currentMoney );
        userAccount.setMoneyBak( currentMoney );
        //当前账户扣除资金(关键词续费款)
        resultCode *= asAccountDao.updateAccount( userAccount );
        //查询财务人员账户信息
        AsAccount financialAccount = new AsAccount();
        Map<String,Object> map = asAccountDao.getFinancialUserAccount();
        //获取财务账户version
        Integer financialVersion = (Integer)map.get( "version" );
        financialAccount.setUserId( (Integer)map.get( "userId" ) );
        Double financialTotalMoney = (Double)map.get( "money" );
        Double financialCurrentMoney = financialTotalMoney + totalPrice;
        financialAccount.setMoney( financialCurrentMoney );
        financialAccount.setMoneyBak( financialCurrentMoney );
        financialAccount.setVersion( financialVersion );
        //财务人员账户增加资金(关键词续费款)
        resultCode *= asAccountDao.updateAccount( financialAccount );

        //向账户明细表中添加数据
        //查询财务款项操作名称
        AsSystemConfig config = asSystemConfigDao.getFinancialType( detailType );
        AsAccountDetail detail = new AsAccountDetail();
        detail.setUserId( userId );
        detail.setDetailType( detailType );
        detail.setDetailTypeName( "[系统自动]" + config.getConfigValue() );
        detail.setMoney( totalPrice );
        detail.setAccountMoney( currentMoney );
        detail.setDetailDateTime( new Date() );
        detail.setMemo( "[" + user.getUserName() + "]为客户[" + keywords.getCustomName() +
                "]进行关键词(" + keywords.getKeywords() + ")续费操作; 扣除[" + user.getUserName() + "]资金:" + totalPrice + "元" );
        resultCode *= asAccountDetailDao.addOneDetail( detail );

        //确保任意步骤执行失败(resultCode为0)后回滚
        if( resultCode == 0 )
        {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return resultCode;
    }

    //提交关键词审核通过,返回提交结果(增加乐观锁)
    //通过注解开启事务管理 只要出现异常即回滚
    @Transactional( rollbackFor = Exception.class )
    public Integer submitKeywordsIsOk( Integer id , Integer detailType ,  AsUser user )
    {
        Integer resultCode = 0;
        //根据id查询对应关键词
        AsKeywords keywords = asKeywordsDao.getOneKeyWordById( id );
        //设置关键词审核状态为已通过
        keywords.setCheckStatus( 2 );
        //获取关键词代理的1年费用
        Double oneYearPrice = keywords.getPreRegFrozenMoney();
        //获取服务年限
        Integer years = keywords.getServiceYears();
        //计算并设置代理费用 清空预冻结款
        Double totalPrice = oneYearPrice * years;
        keywords.setPrice( totalPrice );
        keywords.setPreRegFrozenMoney( 0.0 );
        //依照当前时间修改正式申请时间和到期时间
        keywords.setRegDatetime( new Date() );
        Date passDateTime = DateUtil.calculationDate( years.longValue() );
        keywords.setRegPassDatetime( passDateTime );
        //将修改写入关键词表中
        resultCode = asKeywordsDao.updateOneKeywords( keywords );

        //获取关键词代理商id
        Integer userId = keywords.getAgentId();
        //根据用户id获取当前账户
        AsAccount userAccount = asAccountDao.getAccountByUserId( userId );
        //获取当前账户资金
        Double totalMoney = userAccount.getMoney();
        Double currentMoney = totalMoney - totalPrice;
        userAccount.setMoney( currentMoney );
        userAccount.setMoneyBak( currentMoney );
        //代理商账户扣除资金(关键词代理费)
        resultCode *= asAccountDao.updateAccount( userAccount );
        //查询财务人员账户信息
        AsAccount financialAccount = new AsAccount();
        Map<String,Object> map = asAccountDao.getFinancialUserAccount();
        //获取财务账户version
        Integer financialVersion = (Integer)map.get( "version" );
        financialAccount.setUserId( (Integer)map.get( "userId" ) );
        Double financialTotalMoney = (Double)map.get( "money" );
        Double financialCurrentMoney = financialTotalMoney + totalPrice;
        financialAccount.setMoney( financialCurrentMoney );
        financialAccount.setMoneyBak( financialCurrentMoney );
        financialAccount.setVersion( financialVersion );
        //财务人员账户增加资金(关键词代理费)
        resultCode *= asAccountDao.updateAccount( financialAccount );

        //向账户明细表中添加数据
        //查询财务款项操作名称
        AsSystemConfig config = asSystemConfigDao.getFinancialType( detailType );
        AsAccountDetail detail = new AsAccountDetail();
        detail.setUserId( userId );
        detail.setDetailType( detailType );
        detail.setDetailTypeName( "[系统自动]" + config.getConfigValue() );
        detail.setMoney( totalPrice );
        detail.setAccountMoney( currentMoney );
        detail.setDetailDateTime( new Date() );
        detail.setMemo( "[" + user.getUserName() + "]为客户[" + keywords.getCustomName() +
                "]进行关键词(" + keywords.getKeywords() + ")审核通过操作; 扣除[" + keywords.getAgentName() + "]资金:" + totalPrice + "元" );
        resultCode *= asAccountDetailDao.addOneDetail( detail );

        //确保任意步骤执行失败(resultCode为0)后回滚
        if( resultCode == 0 )
        {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return resultCode;
    }

    //提交开通App,返回提交结果(增加乐观锁)
    //通过注解开启事务管理 只要出现异常即回滚
    @Transactional( rollbackFor = Exception.class )
    public Integer submitOpenApp(
            Integer id , String appUserName , String appPassword ,
            Double appPrice , Integer detailType ,  AsUser user )
    {
        Integer resultCode = 0;
        Integer userId = user.getId();
        //根据id查询对应关键词
        AsKeywords keywords = asKeywordsDao.getOneKeyWordById( id );
        //设置app状态为开通
        keywords.setOpenApp( true );
        //设置app账号和密码
        keywords.setAppUserName( appUserName );
        keywords.setAppPassword( appPassword );
        //更新价格
        Double oldPrice = keywords.getPrice();
        keywords.setPrice( oldPrice + appPrice );
        //将修改写入表
        resultCode = asKeywordsDao.updateOneKeywords( keywords );

        //根据用户id获取当前账户
        AsAccount userAccount = asAccountDao.getAccountByUserId( userId );
        //获取当前账户资金
        Double totalMoney = userAccount.getMoney();
        Double currentMoney = totalMoney - appPrice;
        userAccount.setMoney( currentMoney );
        userAccount.setMoneyBak( currentMoney );
        //当前账户扣除资金(开通app资金)
        resultCode *= asAccountDao.updateAccount( userAccount );
        //查询财务人员账户信息
        AsAccount financialAccount = new AsAccount();
        Map<String,Object> map = asAccountDao.getFinancialUserAccount();
        //获取财务账户version
        Integer financialVersion = (Integer)map.get( "version" );
        financialAccount.setUserId( (Integer)map.get( "userId" ) );
        Double financialTotalMoney = (Double)map.get( "money" );
        Double financialCurrentMoney = financialTotalMoney + appPrice;
        financialAccount.setMoney( financialCurrentMoney );
        financialAccount.setMoneyBak( financialCurrentMoney );
        financialAccount.setVersion( financialVersion );
        //财务人员账户增加资金(开通app资金)
        resultCode *= asAccountDao.updateAccount( financialAccount );

        //向账户明细表中添加数据
        //查询财务款项操作名称
        AsSystemConfig config = asSystemConfigDao.getFinancialType( detailType );
        AsAccountDetail detail = new AsAccountDetail();
        detail.setUserId( userId );
        detail.setDetailType( detailType );
        detail.setDetailTypeName( "[系统自动]" + config.getConfigValue() );
        detail.setMoney( appPrice );
        detail.setAccountMoney( currentMoney );
        detail.setDetailDateTime( new Date() );
        detail.setMemo( "[" + user.getUserName() + "]为客户[" + keywords.getCustomName() +
                "]进行关键词(" + keywords.getKeywords() + ")开通APP操作; 扣除[" + user.getUserName() + "]资金:" + appPrice + "元" );
        resultCode *= asAccountDetailDao.addOneDetail( detail );

        //确保任意步骤执行失败(resultCode为0)后回滚
        if( resultCode == 0 )
        {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }

        return resultCode;
    }

}
